package com.example.myapplication1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.example.myapplication1.Bean.User;

import org.litepal.LitePal;

import java.util.List;

public class LoginActivity extends AppCompatActivity {
    private EditText usnedit, psdedit;
    private Button loginbtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_actibing);
        //获取初始数据
        getUser();
        initView();
        //监听器
        setListener();


    }
    private void setListener() {
        //监听登录
        loginbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String usn = usnedit.getText().toString().trim();
                String psd = psdedit.getText().toString().trim();
                User user = confimUser(usn, psd);
                if (user == null) {
                    //登录失败
                } else {
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    SharedPreferences sp=getSharedPreferences("userinfo",MODE_PRIVATE);
                    SharedPreferences.Editor editor=sp.edit();
                    editor.putInt("myid",user.getId());
                    editor.putString("myname",user.getName());
                    editor.putInt("myimg",user.getUsering());
                    editor.apply();
                startActivity(intent);
                }
            }
        });
    }
    private  User  confimUser(String usn,String psd){
        List<User> userList= LitePal.findAll(User.class);
        for (User u:userList){
            if (usn.equals(u.getName())&&psd.equals(u.getPassword())){
                return  u;
            }
        }
        return  null;
    }

    private void getUser() {
        User user=new User(0,"王大姐","123");
        User user1=new User(1,"李大娘","456");
        User user2=new User(2,"梅阿姨","789");
        User user3=new User(3,"孟小姐","803");
        user.save();
        user1.save();
        user2.save();
        user3.save();
    }

    private void initView() {
        usnedit=findViewById(R.id.userid);
        psdedit=findViewById(R.id.psdedit);
        loginbtn=findViewById(R.id.loginbtn);
    }
}
